<script setup>
import { ref, onMounted, nextTick, getCurrentInstance, watch } from "vue";
import chatBox from "@/assets/imgs/pages/invite/box.png";
import inviteBgc from "@/assets/imgs/pages/invite/inviteBgc.png";
import people from "@/assets/imgs/pages/invite/people.png";
import { onLoad } from "@dcloudio/uni-app";

import { useUserStore, usePaintingStore } from "@/store";

import config from "@/config/config.json";
import { getToken } from "@/utils/auth";

const props = defineProps({
  openPopup: Boolean,
});

const emit = defineEmits(["close"]);

const userStore = useUserStore();
const paintingStore = usePaintingStore();
const current = getCurrentInstance();
const accountInfo = wx.getAccountInfoSync();
const popupInviteCode = ref("");
let myCanvas;
let dpr = uni.getSystemInfoSync().pixelRatio;
let imgPath = ref("");

class CanvasPerson {
  canvasId;
  ctx;
  constructor(canvasId) {
    this.canvasId = canvasId;
    this.ctx = null;
  }

  async init() {
    const query = wx.createSelectorQuery().in(current);
    query
      .select(`#${this.canvasId}`)
      .fields({ node: true, size: true })
      .exec((res) => {
        this.canvas = res[0].node;
        this.ctx = this.canvas.getContext("2d");
        let dpr = uni.getSystemInfoSync().pixelRatio;
        this.canvas.width = 500 * dpr;
        this.canvas.height = 700 * dpr;
        this.ctx.scale(dpr, dpr);
      });
    await new Promise((res) => setTimeout(res, 400)); // 确保上下文已准备就绪
  }

  drawRoundRect(x, y, width, height, radius, color) {
    this.ctx.fillStyle = color;
    this.ctx.beginPath();
    this.ctx.moveTo(x + radius, y); // 左上角
    this.ctx.lineTo(x + width - radius, y); // 右上角
    this.ctx.arc(
      x + width - radius,
      y + radius,
      radius,
      (Math.PI * 3) / 2,
      0,
      false
    ); // 右上角圆弧
    this.ctx.lineTo(x + width, y + height - radius); // 右下角
    this.ctx.arc(
      x + width - radius,
      y + height - radius,
      radius,
      0,
      Math.PI / 2,
      false
    ); // 右下角圆弧
    this.ctx.lineTo(x + radius, y + height); // 左下角
    this.ctx.arc(
      x + radius,
      y + height - radius,
      radius,
      Math.PI / 2,
      Math.PI,
      false
    ); // 左下角圆弧
    this.ctx.lineTo(x, y + radius); // 左上角
    this.ctx.arc(
      x + radius,
      y + radius,
      radius,
      Math.PI,
      (Math.PI * 3) / 2,
      false
    ); // 左上角圆弧
    this.ctx.closePath();
    this.ctx.stroke();
    this.ctx.fill();
    this.ctx.save();
    this.ctx.clip();
  }
  drawImage(src, x, y, width, height, beforDraw, afterDraw) {
    let img = this.canvas.createImage();
    img.src = src;
    img.onload = () => {
      beforDraw && beforDraw();
      this.ctx.drawImage(img, x, y, width, height);
      afterDraw && afterDraw();
    };
  }
  drawText(text, x, y, size, color) {
    this.ctx.fillStyle = color;
    this.ctx.font = size;
    this.ctx.fillText(text, x, y);
  }
}

const getPopupInviteCodeFn = async () => {
  const res = await uni.request({
    url: `${config.siteDomain}${import.meta.env.VITE_GLOB_API_URL
      }/wechat/getUnlimitedQRCode`,
    header: {
      satoken: getToken(),
    },
    data: {
      envVersion: accountInfo.miniProgram.envVersion,
    },
    responseType: "arraybuffer",
  });
  popupInviteCode.value =
    "data:image/png;base64," + wx.arrayBufferToBase64(res.data);
};

const close = () => {
  emit("close");
};

// 自定义绘制圆角矩形的函数
function drawRoundRect(ctx, x, y, width, height, radius) {
  ctx.beginPath();
  ctx.moveTo(x + radius, y); // 左上角
  ctx.lineTo(x + width - radius, y); // 右上角
  ctx.arc(x + width - radius, y + radius, radius, (Math.PI * 3) / 2, 0, false); // 右上角圆弧
  ctx.lineTo(x + width, y + height - radius); // 右下角
  ctx.arc(
    x + width - radius,
    y + height - radius,
    radius,
    0,
    Math.PI / 2,
    false
  ); // 右下角圆弧
  ctx.lineTo(x + radius, y + height); // 左下角
  ctx.arc(x + radius, y + height - radius, radius, Math.PI / 2, Math.PI, false); // 左下角圆弧
  ctx.lineTo(x, y + radius); // 左上角
  ctx.arc(x + radius, y + radius, radius, Math.PI, (Math.PI * 3) / 2, false); // 左上角圆弧
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

const createCanvas = async () => {
  myCanvas = new CanvasPerson("canvas");
  await myCanvas.init();
  myCanvas.drawRoundRect(0, 0, 500, 700, 40, "#1C0E39");
  myCanvas.drawImage(inviteBgc, 0, 0, 500, 700, undefined, () => {
    myCanvas.drawImage(
      userStore.userInfo.avatarUrl,
      200,
      30,
      100,
      100,
      () => {
        myCanvas.ctx.beginPath();
        myCanvas.ctx.arc(250, 80, 50, 0, 2 * Math.PI);
        myCanvas.ctx.save();
        myCanvas.ctx.clip();
      },
      () => {
        myCanvas.ctx.restore();
      }
    );
    myCanvas.drawImage(people, 300, 110, 180, 180, undefined, () => {
      myCanvas.drawImage(chatBox, 50, 165, 192, 88, undefined, () => {
        myCanvas.drawText("图文带货助手", 60, 210, "28px Arial", "#FFF");
        myCanvas.drawText(
          "文案生成绘图创作一应俱全，",
          60,
          350,
          "28px Arial",
          "#FFF"
        );
        myCanvas.drawText("大大提高爆单几率。", 60, 400, "28px Arial", "#FFF");
        myCanvas.ctx.beginPath();
        myCanvas.drawRoundRect(150, 460, 200, 200, 30);
        myCanvas.drawImage(
          popupInviteCode.value,
          150,
          460,
          200,
          200,
          undefined,
          () => {
            myCanvas.ctx.restore();
          }
        );
      });
    });
  });
};

// const createCanvas = () => {
//   const query = uni.createSelectorQuery().in(current);

//   query
//     .select("#canvas")
//     .fields({ node: true, size: true })
//     .exec((res) => {
//       myCanvas = res[0].node;
//       myCanvas.width = 500 * dpr;
//       myCanvas.height = 700 * dpr;
//       let ctx = myCanvas.getContext("2d");
//       ctx.scale(dpr, dpr);
//       ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
//       ctx.fillStyle = "#1C0E39"; // 设置填充色
//       // ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);
//       drawRoundRect(ctx, 0, 0, 500, 700, 40);
//       let bgImg = myCanvas.createImage();
//       bgImg.src = inviteBgc;
//       bgImg.onload = () => {
//         ctx.drawImage(bgImg, 0, 0, 500, 700);
//       };
//       const avatarImg = myCanvas.createImage();
//       avatarImg.src = userStore.userInfo.avatarUrl;
//       avatarImg.onload = () => {
//         const currX = myCanvas.width / 2 / dpr;
//         const currY = 80;
//         const r = 50;
//         ctx.arc(currX, currY, r, 0, 2 * Math.PI);
//         ctx.save();
//         ctx.clip();
//         ctx.drawImage(avatarImg, currX - r, currY - r, r * 2, r * 2);
//         ctx.restore();
//       };
//       const peopleImg = myCanvas.createImage();
//       peopleImg.src = people;
//       peopleImg.onload = () => {
//         const currX = myCanvas.width / dpr - 220;
//         const currY = 130;
//         ctx.drawImage(
//           peopleImg,
//           currX,
//           currY,
//           peopleImg.width * 1.2,
//           peopleImg.height * 1.2
//         );
//       };
//       const chatImage = myCanvas.createImage();
//       chatImage.src = chatBox;
//       chatImage.onload = () => {
//         const currX = 50;
//         const currY = 180;
//         ctx.drawImage(
//           chatImage,
//           currX,
//           currY,
//           chatImage.width,
//           chatImage.height
//         );
//         ctx.font = "28px Arial";
//         ctx.fillStyle = "#fff";
//         ctx.fillText("图文带货助手", currX + 10, currY + 46);
//         ctx.fillText("文案生成绘图创作一应俱全，", currX + 10, currY + 160);
//         ctx.fillText("大大提高爆单几率。", currX + 10, currY + 210);
//       };

//       const codeImage = myCanvas.createImage();
//       codeImage.src = popupInviteCode.value;
//       codeImage.onload = () => {
//         const currX = 250;
//         const currY = 450;
//         ctx.strokeStyle = "#FFF";
//         ctx.lineWidth = 6;
//         drawRoundRect(ctx, currX - 110, currY, 220, 220, 30);
//         ctx.fillStyle = "rgba(255,255,255,0.2)";
//         ctx.fill();
//         drawRoundRect(ctx, 150, 460, 200, 200, 30);
//         ctx.save();
//         ctx.clip();
//         ctx.drawImage(
//           codeImage,
//           145,
//           460,
//           codeImage.width * 0.5,
//           codeImage.height * 0.5
//         );
//         ctx.restore();
//       };
//       setTimeout(() => {
//         imgPath.value = myCanvas?.toDataURL();
//       }, 400);
//     });
// };

const clickFn = () => {
  uni.previewImage({
    urls: [imgPath.value],
    current: imgPath.value,
  });
};

const saveImg = () => {
  paintingStore.accredit({
    canvas: myCanvas.canvas,
    path: myCanvas.canvas?.toDataURL(),
  });
  // imgPath.value = myCanvas.canvas?.toDataURL();
  // uni.previewImage({
  //   urls: [imgPath.value],
  //   current: imgPath.value,
  // });
};

watch(() => props.openPopup, (val) => {
  if (val) {
    createCanvas();
  }
}, { deep: true, immediate: true });

onLoad(async () => {
  await getPopupInviteCodeFn();
  // createCanvas();
});
</script>

<template>
  <van-popup :show="openPopup" round @close="close">
    <div class="canvasBox">
      <canvas type="2d" id="canvas" style="width: 500rpx; height: 700rpx"></canvas>
      <button @click="saveImg" class="saveBtn">点击保存海报</button>
    </div>
  </van-popup>
</template>

<style lang="less" scoped>
.canvasBox {
  width: 500rpx;
  height: 850rpx;
  margin-bottom: 22.5rpx;
  position: relative;

  .canvas {
    width: 500rpx;
    height: 700rpx;
  }

  .imgSty {
    width: 500rpx;
    height: 700rpx;
  }

  .saveBtn {
    position: absolute;
    bottom: 50rpx;
    left: 50%;
    transform: translate(-50%);
    min-width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    border-radius: 30rpx;
    letter-spacing: 2rpx;
    font-size: 24rpx;
    color: var(--a-main-Feature-text-color);
    background-color: var(--a-main-color);
  }
}
</style>
